package hn.security.configuration;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {


    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;


    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler;

    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;

    @Autowired
    private LogoutSuccessHandler logoutSuccessHandler;

    @Autowired
    private AccessDeniedHandler accessDeniedHandler;

    @Autowired
    private ExpiredSessionStrategyImpl expiredSessionStrategyImpl;

    // @Autowired
    // private AuthenticationProvider authenticationProvider;

    // @Autowired
    // private AccessDecisionManager accessDecisionManager;
    //
    // @Autowired
    // private SecurityMetadataSourceImpl securityMetadataSource;
    //
    // @Autowired
    // private SecurityInterceptorFilter securityInterceptorFilter;


    // @Bean
    // public BCryptPasswordEncoder passwordEncoder() {
    //     //密文密码
    //     return new BCryptPasswordEncoder();
    // }

    @Autowired
    private CsrfRequestMatcherImpl csrfRequestMatcherImpl;

    @Bean
    public CsrfRequestMatcherImpl csrfRequestMatcherImpl() {
        CsrfRequestMatcherImpl csrfRequestMatcherImpl = new CsrfRequestMatcherImpl();
        List<String> execludeUrls = new ArrayList<>();
        execludeUrls.add("/");
        csrfRequestMatcherImpl.setExecludeUrls(execludeUrls);
        return csrfRequestMatcherImpl;
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // super.configure(auth);
        auth.userDetailsService(userDetailsService);//用户详情服务
        // auth.authenticationProvider(authenticationProvider);//其他登录方式
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // super.configure(http);

        http.cors();

        http.csrf().disable();
        // http.csrf().requireCsrfProtectionMatcher(csrfRequestMatcherImpl);

        // http.addFilterBefore(securityInterceptorFilter, FilterSecurityInterceptor.class);//增加到默认拦截链中

        // 配置权限
        http.authorizeRequests()
                // .antMatchers("/**").fullyAuthenticated()
                .antMatchers("/swagger-ui/**").permitAll()
                .antMatchers("/api/**").permitAll()
                // .antMatchers("/api/**").fullyAuthenticated()
                // .antMatchers("/api/getAllApi").hasAuthority("system")

                // .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                //     @Override
                //     public <O extends FilterSecurityInterceptor> O postProcess(O o) {
                //         o.setAccessDecisionManager(accessDecisionManager);//访问决策管理器
                //         o.setSecurityMetadataSource(securityMetadataSource);//安全元数据源
                //         return o;
                //     }
                // })

                //登录
                .and().formLogin().permitAll()//允许所有用户
                .loginProcessingUrl("/login")
                .usernameParameter("username")
                .passwordParameter("password")
                .successHandler(authenticationSuccessHandler)//登录成功处理逻辑
                .failureHandler(authenticationFailureHandler)//登录失败处理逻辑


                //退出
                .and().logout().permitAll()//允许所有用户
                .logoutUrl("/logout")
                .logoutSuccessHandler(logoutSuccessHandler)//退出成功处理逻辑
                .deleteCookies("JSESSIONID")//退出之后删除cookie(JSESSIONID)

                // 异常处理
                .and().exceptionHandling()
                .accessDeniedHandler(accessDeniedHandler)
                .authenticationEntryPoint(authenticationEntryPoint)

                //回话管理
                .and().sessionManagement().maximumSessions(1)
                .expiredSessionStrategy(expiredSessionStrategyImpl)

        ;


    }
}
